package com.qf.controller;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.text.RandomStringGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
@CrossOrigin("*")
public class FileController {
    @Value("${fileUplaodLocation}")
    private String fileUploadLocation;

//    @Value("fileHttpURL")
//    private String fileHttpURL;


    @PostMapping("/upload")
    public Object upload(MultipartFile uploadFile) throws FileUploadException {
        System.out.println("==========================");
       // NonBlockingHashMap<String,String> map = new NonBlockingHashMap<>();
        Map<String,String> map = new HashMap<>();
        long size = uploadFile.getSize();

         // 文件名需要修改：1.文件重名的问题；2.防止恶意用户有些违规的文件名; 3.实现文件名的统一。
        String originFileName = uploadFile.getOriginalFilename();

        // 获取文件的后缀名：  .jpg  .png  .mp4
        String fileNameSuffix = originFileName.substring(originFileName.lastIndexOf("."));

        // 随机字符串生成器
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange(new char[]{'a', 'z'}, new char[]{'A', 'Z'}, new char[]{'0', '9'}).build();

        // System.nanoTime() 是当前系统从1970至今的纳秒时间，
        String newFileName = System.nanoTime() + generator.generate(10) + fileNameSuffix;

        try {
            uploadFile.transferTo(new File(fileUploadLocation + newFileName));
            map.put("headImgUrl",newFileName);
            return map;
        }catch (IOException ioException) {
            ioException.printStackTrace();
            throw new FileUploadException("文件上传失败");
        }
    }



}
